#include <iostream>
#include <string>
#include <memory>
#include <sstream>
#include "jsoncpp/json/json.h"

using namespace std;


bool serialize(Json::Value& root, string& body)
{
    // 这个StreamWriterBuilder是StreamWriter的子类对象
    Json::StreamWriterBuilder swb;
    // 因为StreamWriter是抽象类 不可以直接实例化出对象 所以用基类指针指向子类函数 多态
    unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    stringstream ss;
    int ret = sw->write(root, &ss);
    if(ret != 0)
    {
        cout << "serialize failed!" << endl;
        return false;
    }
    body = ss.str();
    return true;
}

bool deserialize(const string& body, Json::Value& root)
{
    // 这个CharReaderBuilder是CharReader的子类对象
    Json::CharReaderBuilder crb;
    // 因为CharReader是抽象类对象 不能实例化出对象 所以用基类指针指向子类对象
    unique_ptr<Json::CharReader> cr(crb.newCharReader());
    
    string serr;
    int ret = cr->parse(body.c_str(), body.c_str() + body.size(), &root, &serr);
    if(ret == 0)
    {
        cout << "deserialize failed!" << endl;
        return false;
    }
    return true;
}

int main()
{
    const char* name = "zhangsan";
    int age = 10;
    float socres[3] = {77, 88.5, 99};

    Json::Value root;
    root["name"] = name;
    root["age"] = age;
    root["socres"].append(socres[0]);
    root["socres"].append(socres[1]);
    root["socres"].append(socres[2]);

    string body;
    serialize(root, body);
    cout << body << endl;

    Json::Value tem;
    deserialize(body, tem);

    cout << tem["name"].asString() << endl;
    cout << tem["age"].asInt() << endl;
    int n = tem["socres"].size();

    for(int i = 0; i < n; i++)
    {
        cout << tem["socres"][i].asFloat() << " ";
    }

    cout << endl;

    return 0;
}